package com.gitee.wsl.android.ext.okhttp.intercept.base

import com.gitee.wsl.android.ext.device.NetworkExt.isNetworkAvailable
import com.gitee.wsl.jvm.okhttp.OkHttpClientScope
import com.gitee.wsl.jvm.okhttp.intercept.base.CacheHeaderSettingInterceptor
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import timber.log.Timber
import java.io.IOException

/**
 *
 * 描述：支持离线缓存,使用OKHttp自带的缓存功能
 *
 *
 * 配置OKHttp的Cache<br></br>
 * 配置请求头中的cache-control或者统一处理所有请求的请求头<br></br>
 * 云端配合设置响应头或者自己写拦截器修改响应头中cache-control<br></br>
 * 列：<br></br>
 *
 *
 * 在Retrofit中，我们可以通过@Headers来配置，如：
 *
 *
 * `@Headers("Cache-Control: public, max-age=3600)`
 * `@GET("merchants/{shopId}/icon") Observable<ShopIconEntity> getShopIcon(@Path("shopId") long shopId);`
 *
 *
 * 如果你不想加入公共缓存，想单独对某个api进行缓存，可用Headers来实现<br></br>
 *
 *
 * 请参考网址：http://www.jianshu.com/p/9c3b4ea108a7<br></br>
 *
 * @author xuexiang
 * @since 2018/6/22 上午9:48
 */
class CacheOfflineHeaderSettingInterceptor : CacheHeaderSettingInterceptor() {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var request: Request = chain.request()
        if (!isNetworkAvailable) {
            Timber.i(" no network load cache:" + request.cacheControl.toString())
            /* request = request.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "only-if-cached, " + cacheControlValue_Offline)
                    .build();*/
            request = request.newBuilder()
                .cacheControl(CacheControl.FORCE_CACHE) //.cacheControl(CacheControl.FORCE_NETWORK)
                .build()
            val response: Response = chain.proceed(request)
            return response.newBuilder()
                .removeHeader("Pragma")
                .removeHeader("Cache-Control")
                .header("Cache-Control", "public, only-if-cached, $cacheControlValue_Offline")
                .build()
        }
        return chain.proceed(request)
    }
}

fun OkHttpClientScope.ableOfflineUseCache() {
    getBuilder().addInterceptor(CacheOfflineHeaderSettingInterceptor())
}